package cdc.mvp.presenter;


import com.alibaba.fastjson.JSONObject;
import com.cdc.retrofit.Api;
import com.cdc.retrofit.RetrofitManager;
import com.cdc.urls.FileResult;
import com.cdc.urls.Person;
import com.cdc.urls.User;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cdc.mvp.view.RequestView;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cdc on 2018/4/25.
 */

public class RequestPresenterImpl implements RequestPresenter{

    private RequestView requestView;

    private RetrofitManager retrofitManager;

    private Api api;
    @Override
    public void attachView(RequestView v) {
        this.requestView=v;
        retrofitManager=RetrofitManager.getSingleton();
        api=retrofitManager.apiservice();

    }

    @Override
    public void detachView() {
        requestView=null;
    }

    @Override
    public void personBody() {
        Call<ResponseBody> call=api.personBody();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String  result= null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                requestView.success(result);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                httpError(call );
            }
        });
    }

    /**
     *
     * restful  api
     * api/person/3
     * @param id
     */
    public void restPerson(Integer id) {
        Call<Person> call=api.restPathPerson(id);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    Person result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }

            }

            @Override
            public void onFailure(Call<Person> call, Throwable t) {
               httpError(call);
            }
        });
    }

    private void httpError(Call<?> call){
        StringBuilder sb=new StringBuilder("method_url:");
        sb.append("\r\n");
        sb.append(urlMethod(call.request()));
        sb.append("\r\n");
        sb.append(headers(call.request()));
        requestView.error(sb.toString());
    }

    /**
     * restful
     *
     * api/user/3
     * @param id
     */
    @Override
    public void restUser(Integer id) {
        Call<User> call=api.restPathUser(id);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    User result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }

            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                httpError(call);
            }
        });
    }

    @Override
    public void personBothQueryMap(Integer id, String name) {
        Map<String,Object> paramers=new HashMap<>();
        paramers.put("id",id);
        paramers.put("name",name);
        Call<Person> call=api.personBothQueryMap(paramers);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    Person result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }

            }

            @Override
            public void onFailure(Call<Person> call, Throwable t) {
                httpError(call);
            }
        });
    }

    @Override
    public void personBothQuary(Integer id, String name) {
        Call<Person> call=api.personBothQuary(id,name);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    Person result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }
            @Override
            public void onFailure(Call<Person> call, Throwable t) {
                httpError(call);
            }
        });
    }

    @Override
    public void personBothForm(Integer id, String name) {
        Call<Person> call=api.personBothForm(id,name);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    Person result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }
            @Override
            public void onFailure(Call<Person> call, Throwable t) {
                httpError(call);
            }
        });
    }

    @Override
    public void upPerson(Person person) {
        String route = JSONObject.toJSONString(person);// 通过Json将Bean转化为Json字符串形式
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), route);
        Call<Person> call = api.upPerson(body);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    Person result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }
            @Override
            public void onFailure(Call<Person> call, Throwable t) {
                httpError(call);
            }
        });
    }

    @Override
    public void uploadPerson(File file, Integer id, String name) {
        // 创建RequestBody，传入参数："multipart/form-data"，String
        RequestBody requestIdKey = RequestBody.create(MediaType.parse("multipart/form-data"), id + "");
        RequestBody requestNameKey = RequestBody.create(MediaType.parse("multipart/form-data"), name);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part bodyFile = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        Call<FileResult> call = api.uploadPerson(bodyFile, requestIdKey, requestNameKey);
        call.enqueue(new Callback<FileResult>() {
            @Override
            public void onResponse(Call<FileResult> call, Response<FileResult> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    FileResult result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }

            @Override
            public void onFailure(Call<FileResult> call, Throwable t) {
                httpError(call);
            }
        });

    }

    @Override
    public void uploadPerson(File file, String idKey,Integer id, String nameKey,String name) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart(idKey, id+"")
                .addFormDataPart(nameKey, name).addFormDataPart("file", file.getName(), requestFile).build();
        Call<FileResult> call = api.uploadPerson(requestBody);
        call.enqueue(new Callback<FileResult>() {
            @Override
            public void onResponse(Call<FileResult> call, Response<FileResult> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    FileResult result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }

            @Override
            public void onFailure(Call<FileResult> call, Throwable t) {
                httpError(call);
            }
        });

    }

    @Override
    public void uploadsPerson(String idKey,Integer id, String nameKey,String name,File ...files) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart(idKey, id+"")
                .addFormDataPart(nameKey, name);
        int length=files.length;
        for (int i=0;i<length;i++){
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files[i]);
            builder.addFormDataPart("file", files[i].getName(), requestFile);
        }
        RequestBody requestBody=builder.build();
        Call<FileResult> call = api.uploadsPerson(requestBody);
        call.enqueue(new Callback<FileResult>() {
            @Override
            public void onResponse(Call<FileResult> call, Response<FileResult> response) {
                boolean bl=response.isSuccessful();
                if(bl){
                    FileResult result = response.body();
                    requestView.success(result.toString());
                }else{
                    requestView.success(response.code()+"");
                }
            }

            @Override
            public void onFailure(Call<FileResult> call, Throwable t) {
                httpError(call);
            }
        });

    }





    private String urlMethod(Request request) {
        StringBuilder sb=new StringBuilder("method:");
        sb.append("method:");
        String method = request.method();
        sb.append(method);
        sb.append("\r\n");
        sb.append("url:");
        String url = request.url().url().toString();
        sb.append(url);
        sb.append("\r\n");
        return sb.toString();
    }

    /**
     * 打印请求头
     *
     * @param request
     */
    private String  headers(Request request) {
        Headers headers = request.headers();
        int size = headers.size();
        if(size!=0){
            StringBuilder sb=new StringBuilder("请求头:");
            for (int i = 0; i < size; i++) {
                String name = headers.name(i);
                String value = headers.value(i);
                sb.append("\r\n");
                sb.append("header_name=");
                sb.append(name);
                sb.append("header_value=");
                sb.append(value);
            }
            return sb.toString();
        }
        return "";

    }
}
